import { delPageList, getPageList } from '@/services/modules/page';
import { delSearchList, getSearchList, selectSearchList } from '@/services/modules/search';
import {  ISearchList } from '@/types';
import { Effect,  Reducer } from 'umi';

export interface SearchModelState {
    searchList: ISearchList [],
    searchLength: number,
    selectSearchList: ISearchList [],
    selectSearchLength:number
}

export interface SearchModelType {
  namespace: 'search';
  state: SearchModelState;
  effects: {
    getSearchList:Effect;
    delSearchList:Effect;
    selectSearchList:Effect;
  };
  reducers: {
    save: Reducer<SearchModelState>;
  };
}

const PageModel: SearchModelType = {
  // 数据模型，用来隔离数据防止相互影响
  namespace: 'search',

  // 数据模型状态，相当于vuex的state
  state: {
    searchList:[],
    searchLength:0,
    selectSearchList:[],
    selectSearchLength: 0
  },

  // 异步操作，相当于vuex的action
  effects: {
    // 先简单记忆，*相当于async，yield相当于await
    // 获取
    *getSearchList({payload},{call,put}){
        let res= yield call(getSearchList,payload);
        console.log(res)
        if(res.data){
            yield put({
                type:'save',
                payload:{
                    searchList:res.data[0],
                    searchLength:res.data[1]
                }
            })
        }
    },
    // 删除
    *delSearchList({payload},{call,put}){
      let res= yield call(delSearchList,payload);      
    },
    // 筛选
    *selectSearchList({payload},{call,put}){
      let res = yield call(selectSearchList,payload);
      if(res.data){
        yield put({
          type:'save',
          payload:{
            selectSearchList:res.data[0],
            selectSearchLength: res.data[1]
          }
        })
      }
    }
  },

  // 同步操作，相当于vuex的mutation
  reducers: {
    save(state, action) {
      return {
        ...state,
        ...action.payload,
      };
    },

  }
};

export default PageModel;
